# -*- coding: utf_8 -*-
# @Create   : 2021/8/30 10:18
# @Author   : yh
# @Remark   : 巡检计划server层
import logging
import time
import os
from typing import List

from mxsoftpy import Server
from mxsoftpy.exception import DataError

from db.common.VideoManage.VideoQuality.inspection_plan import InspectionPlanDB
from model.common.VideoManage.VideoQuality.inspection_plan import InspectionPlanModel, InspectionPlanUpdateModel
from utils.conf.mxconfig import MxConfig
from utils.public.export_execl import ExportExecl
from utils.public.params_method import get_pagination_params, pagination


class InspectionPlanServer(Server):
    __db__ = InspectionPlanDB

    def _export_data(self, data):
        """
        转换成导出excl所需格式
        param: data 需要转换的列表
        param：test_name_dict 拼接headline
        """

        data_dict = {
                "header": "巡视计划",
                "headline": {
                    "id": "序号",
                    "name": "计划名称",
                    "task_cycle_name": "计划周期",
                    "begin_time": "开始时间",
                    "principal": "负责人",
                    "data_state": "状态",
                },
                "data": data
        }
        file_name = "plan_" + str(int(time.time())) + ".xlsx"
        return data_dict,file_name

    def create(self, **inspection_plan_model):
        """
        添加巡检计划
        :param inspection_plan_model: 巡检计划模型，详情见InspectionPlanModel类
        """

        inspection_plan = InspectionPlanModel(**inspection_plan_model)
        plan_code = self.db.create(**inspection_plan.dict(exclude={'TestItems': ...}))

        # 完成巡检计划的检测项目添加
        try:
            assert self.db.create_or_update_items(plan_code,
                                                  inspection_plan.dict(include={'TestItems': ...})['TestItems']), ''
            return plan_code
        except Exception:
            self.db.delete([plan_code])
            logging.error('添加一个巡检计划的检测项目时出错，已逻辑删除此计划，计划code: %s' % plan_code)
            raise DataError('添加巡检计划失败')

    def delete(self, plan_code: str):
        """
        删除巡检计划
        :param plan_code: 要删除的计划code，多个使用逗号分隔
        """
        del_list = plan_code.split(';')
        return self.db.delete(del_list)

    def stop(self, plan_code: str):
        """
        停用巡检计划
        :param plan_code: 要停用的计划code，多个使用逗号分隔
        """
        stop_list = plan_code.split(';')
        return self.db.stop(stop_list)

    def start(self, plan_code: str):
        """
        启用巡检计划
        :param plan_code: 要启用的计划code，多个使用分号分隔
        """
        start_list = plan_code.split(';')
        return self.db.start(start_list)

    def start_check(self, plan_code: str) -> List[dict]:
        """
        启用巡检计划校验
        :param start_list: 要启用的计划列表
        """
        start_list = plan_code.split(';')
        return self.db.start_check(start_list)

    def retrieve(self, plan_code: str):
        """
        获取巡检计划详情
        :param plan_code: 要获取的计划code
        """
        return self.db.retrieve(plan_code)

    def update(self, **inspection_plan_update_model):
        """
        更新巡检计划
        :param inspection_plan_update_model: 巡检计划更新模型，详情见InspectionPlanUpdateModel类
        """
        inspection_plan = InspectionPlanUpdateModel(**inspection_plan_update_model)
        plan_code = self.db.update(inspection_plan_update_model['plan_code'],
                                   **inspection_plan.dict(exclude={'TestItems': ...}))

        # 完成巡检计划的检测项目更新
        self.db.create_or_update_items(plan_code, inspection_plan.dict(include={'TestItems': ...})['TestItems'])
        return plan_code

    def select(self, name: str, export_code: str = "", **paging):
        """
        模糊查询巡检计划
        :param name: 计划名称
        :param export_code: 导出标识 1为导出
        :param paging: 分页参数
        """

        query = get_pagination_params(paging)  # 获取分页参数
        query.update({'state': 1, 'name__like': '*%s*' % name, 'order_by': 'create_time', 'is_desc': True})
        total, data = self.db.select(**query)

        # 添加序号
        i = 0
        state_dict = {0: '停用', 1: '启用'}
        for value in data['data']:
            i += 1
            value['id'] = i
            value['data_state'] = state_dict[value['data_state']]

        # 导出Excel
        if export_code == "1":
            data_dict, file_name = self._export_data(data['data'])
            path = MxConfig.TMP_DIR + file_name
            execl_path = os.sep + "tmp" + os.sep + file_name
            if data_dict["data"]:
                try:
                    ExportExecl().data_process(data_dict)(path)
                    logging.info("成功导出excel")
                    return {'execl_path': execl_path}
                except DataError:
                    logging.error("导出excel出错")
                    raise DataError("导出excel出错")

            else:
                raise DataError("数据为空")

        return pagination(data, query, total)
